package com.example.administrator.baseproject;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;

import java.lang.ref.WeakReference;

import customhandler.MyHandler;
import singleton.SingletonClass;


/**
 * A simple {@link Fragment} subclass.
 */
public class RootFragment extends Fragment {


    protected FrameHandler mHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new FrameHandler(this);
    }

    protected void sendEmptyMessage(int what) {
        mHandler.sendEmptyMessage(what);
    }

    protected void sendEmptyMessageDelay(int what, long delay) {
        mHandler.sendEmptyMessageDelayed(what, delay);
    }


    protected void sendMessage(Message msg) {
        mHandler.sendMessage(msg);
    }

    /**
     *
     * @param msg
     */
    protected void onHandleMessage(Message msg) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        SingletonClass.getSingleton(MyHandler.class).unregistHandler(mHandler);
    }

    protected static class FrameHandler extends Handler {

        private WeakReference<RootFragment> activityWrf;

        public FrameHandler(RootFragment fragment) {
            activityWrf = new WeakReference<RootFragment>(fragment);
            SingletonClass.getSingleton(MyHandler.class).registeHandler(this);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (activityWrf != null) {
                RootFragment fragment = activityWrf.get();
                if (fragment != null ) {
                    try {
                        fragment.onHandleMessage(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
